package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.dto.CategoryDTO;
import com.example.dto.UserLoginDTO;
import com.example.entity.User;
import com.example.exception.LoginFailedException;
import com.example.mapper.UserMapper;
import com.example.properties.WeChatProperties;
import com.example.service.UserService;
import com.example.utils.HttpClientUtil;
import com.example.vo.BookDishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //  微信服务接口地址
    public static final String WE_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper  userMapper;


    /**
     * 微信登陆
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        // 调用微信接口服务，获得当前微信用户openid
        Map<String, String> map =new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WE_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        //判读openid是否为空，如果为空登录失败，抛出异常
        if(openid==null){
            throw new LoginFailedException("登录失败！");
        }

        //判断当前是否为新用户
        User user = userMapper.getByOpenid(openid);

        //如果是新用户，完成注册
        if(user ==null){
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();

            userMapper.insert(user);
        }
        //返回用户对象
        return user;
    }


    /**
     * 用户端查询分类
     * @return
     */
    @Override
    public List<CategoryDTO> getCategory() {

        return userMapper.getCategory();
    }

    /**
     * 查询每个分类下的所有图书
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<BookDishVO> getBookDish(Integer categoryId) {

        return userMapper.getBookDish(categoryId);
    }
}
